package com.cwx.mychat.utils.cipher;


import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.spec.KeySpec;
import java.util.Arrays;
import java.util.Base64;

/**
 * 作者： cwx
 * 时间： 2025/5/9 14:53
 * 版本： 1.0
 * 注释： AES工具
 */
@Slf4j
public class AESUtils {

    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final SecureRandom secureRandom = new SecureRandom();

    private static final String password = "1234567890123456";

    // 动态生成密钥（示例）
    private static SecretKey generateKey(String ps, byte[] salt) throws Exception {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec spec = new PBEKeySpec(ps.toCharArray(), salt, 65536, 256);
        return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
    }

    //加密
    public static String encryptLargeData(String plaintext) throws Exception {
        byte[] salt = new byte[16];
        secureRandom.nextBytes(salt);
        SecretKey secretKey = generateKey(password, salt);

        byte[] ivBytes = new byte[16];
        secureRandom.nextBytes(ivBytes);
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);

        // 分块加密
        byte[] plaintextBytes = plaintext.getBytes(StandardCharsets.UTF_8);
        byte[] encryptedBytes = cipher.doFinal(plaintextBytes);

        // 拼接 Salt + IV + 密文
        byte[] combined = new byte[salt.length + ivBytes.length + encryptedBytes.length];
        System.arraycopy(salt, 0, combined, 0, salt.length);
        System.arraycopy(ivBytes, 0, combined, salt.length, ivBytes.length);
        System.arraycopy(encryptedBytes, 0, combined, salt.length + ivBytes.length, encryptedBytes.length);
        log.info("消息加密成功");
        return "加密(" + Base64.getEncoder().encodeToString(combined) + ")";
    }

    //解密
    public static String decryptLargeData(String ciphertext) throws Exception {
        ciphertext = getEncryptedContent(ciphertext);
        byte[] decoded = Base64.getDecoder().decode(ciphertext);
        byte[] salt = Arrays.copyOfRange(decoded, 0, 16);
        byte[] ivBytes = Arrays.copyOfRange(decoded, 16, 32);
        byte[] encryptedBytes = Arrays.copyOfRange(decoded, 32, decoded.length);

        SecretKey secretKey = generateKey(password, salt);
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        log.info("消息解密成功");
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }


    //判断消息是否被加密
    public static boolean isEncrypted(String message) {
        return message.startsWith("加密(") && message.endsWith(")");
    }
    //解析出密文内容
    public static String getEncryptedContent(String message) {
        if (isEncrypted(message)) {
            return message.substring(3, message.length() - 1);
        }
        return message;
    }

    public static void main(String[] args) throws Exception {
        String password = "securePassword123!";
        String originalText = "从前，在一个宁静的小村庄里，住着一位名叫小雨的女孩。小雨非常喜欢大自然，每天都会到森林里探险，观察各种动物和植物。她的梦想是成为一名出色的植物学家，探索世界上所有的植物。\n" +
                "\n" +
                "一天，小雨在森林深处发现了一株从未见过的奇特花朵，花瓣如同彩虹般绚丽多彩，散发着淡淡的香气。小雨被这朵花深深吸引，决定将它带回家进行研究。她小心翼翼地将花移植到自己的花园里，精心浇水，给予阳光和爱护。\n" +
                "\n" +
                "随着时间的推移，这朵花不仅在小雨的花园里茁壮成长，还吸引了许多小动物前来嬉戏。小鸟在花间歌唱，蝴蝶在花瓣上翩翩起舞，整个花园变得生机勃勃。小雨每天都会在花园里观察这些小生命，感受到大自然的美好与和谐。\n" +
                "\n" +
                "然而，有一天，小雨发现花的颜色开始变得暗淡，花瓣也逐渐凋谢。她心急如焚，开始寻找原因。经过一番调查，小雨发现原来是附近的河流被污染，影响了土壤的质量，导致花朵无法正常生长。小雨决定不再袖手旁观，她开始组织村民们一起清理河流，恢复自然的生态环境。\n" +
                "\n" +
                "经过几个月的努力，河流终于恢复了清澈，花园里的花朵也重新焕发了生机。小雨的坚持和努力感动了全村人，大家都意识到保护环境的重要性。从此，村庄里的人们都积极参与环保活动，努力维护大自然的美丽。\n" +
                "\n" +
                "小雨的故事在村庄里传开，激励着更多的人关注自然，爱护环境。她也逐渐成为了一名出色的植物学家，继续探索和研究各种植物，传播环保的理念。小雨用自己的行动告诉大家，只要心中有爱，保护自然的梦想就一定能实现。\uD83C\uDF3C\uD83C\uDF3F";

        String encrypted = encryptLargeData(originalText);
        String decrypted = decryptLargeData("injnwWGxvBnEjFMvTEaU5qhc0sL1DtiN3C3I6NQHNpuDJeyWBoN59B0x96IncllPrOQNHfPHFygO/RCIivakK7IvnkYHAea3GfJiC2Ywf1dgd9GLqv05+d5MfPxvysbnnOEtyKRnUJXtmyReRJ3EFxX9zoR0AdOMF/lDWsPquKmAn96s7uPRCqfOLO6yJyW0ilZ7qrM35O9T1mkrdRqx7NUUlNETMUNbkZHCUvzj71orqoq4Hmkca88n3aYDOzmZBBxuAll6wTmQH3u2q0J/2lKq3UJTB2l/NKiGyNYvjOLBnSNFNaHjg2fAkr+aGjW9TU94t5+HWGF1+cvY1p/ETKfOgU7FDPv7AbMfIaC8XT5i8T1J8G+3SYJFa5/P8JzOyXmr+/XwviJbC08LVd/5IltxZNIof/ZytJxZ3NIVtjryQE+exlBO0Fuq26ohNV/plUJq1AJ3EuJ6BL151DGyFGFoNgUfndQrKrnYl3rCDvPOWooF+2P8KsOdx/IABRqX2325TU4m7z35utTLX3919+5u/OsXJn5/NzTYmQiL0F5MkCmWiiY3jiJ8+kac72Rds0DX0dl/CCUCrdaLfvSB0OqWla0akOONnU4dZlOyJfWr9vk5MtB3QAnYLl9556aRlIewnnslwYac90RoH07G4Dvvv5Abgec/crNRcWWUTq0eM/Dr3fxZJHrOydh0dUt0yi3C+55hOXod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QF9wWm7Li+rRmdQtPatdrI17uuQvauc9V1NaWCZ8XgU4WJ7l9Hdl5wJORiUU4w+dx6ql3ia59BlKVXXfm4NH7Rg86I9LA1PaUIgj+lNnd1ojY2S+Aer3vopnAUn9U40pLNSUcr5EfEXTFPp5qqe70XlMZmqHeks8DdmXnnYgXTNRnhVU5icIhvQNs/FhIzz/PanIg4pd44vWKc9IMWP7ydN3dMc/E0XqZpZSqBgzdWgoXSqoEbg3aW3nJyO/e/4Pdc9V8Sid0cYlWi6Oula+toTtaSIe0FRn4FPCj62qNO2mD3f0pWKAUVfENWDdMXN1jYWdKt3koMXr+a+ImXj3AXjbZor2FuusozEtq8j2SUJvr+fzaSIX+BZ2FBjk1RbzX/7eq+DNRFiuql9AcITKCiqMzoSZ/fN+w5bC5T13qC18xEsVVnG0uKlk2KEosMA0jSm0YaW3ZS1nWKy5qiPPCZy4EVvhLoYfSfhipDSiGEUpTTAm0IDpPleVzs2p/WLAxqUUTtLG4MBP/UJsmshkVjCq2h2OSreo1fE7c2PZ8MWqrmZd30S0/kB6/03ZXXfLnV2OdK8Egec3ZV3QLzyjefA3xAOSn2ibwLCbiHdxDqfssoNY/3ipvVHyACuewVC3ACPm4+Jnt6u4KqZY0NhJ+T7pu9HlW/UgT7OOmwkxds+7jqrf5+1Gw12NncxsVvu0YYpiU0M7+2jiMEUfjYZ6SwRCF1GdyJeYmlLVOdZI=");
        System.out.println("加密结果: " + encrypted);
        System.out.println("解密结果: " + decrypted);

        System.out.println("解密结果长度是否一致: " + (decrypted.length() == originalText.length()));
    }
}
